package com.hbnu.controller;

import com.hbnu.pojo.ApiResult;
import com.hbnu.pojo.LoginRequest;
import com.hbnu.pojo.User;
import com.hbnu.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
@CrossOrigin(origins = "*") // 允许跨域，生产环境建议配置具体域名
public class LoginController {
    
    @Autowired
    private LoginService loginService;
    
    /**
     * 微信小程序登录
     */
    @PostMapping("/wechat/login")
    public ApiResult<Object> wechatLogin(@RequestBody LoginRequest loginRequest) {
        try {
            // 参数校验
            if (loginRequest.getJsCode() == null || loginRequest.getJsCode().trim().isEmpty()) {
                return ApiResult.error(400, "js_code不能为空");
            }
            
            Map<String, Object> result = loginService.wechatLogin(loginRequest);
            
            if ((Boolean) result.get("success")) {
                return ApiResult.success("登录成功", result);
            } else {
                return ApiResult.error((String) result.get("message"));
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.error("登录失败: " + e.getMessage());
        }
    }
    
    /**
     * 测试接口
     */
    @GetMapping("/test")
    public ApiResult<String> test() {
        return ApiResult.success("API服务正常运行");
    }
    
    /**
     * 获取用户信息（需要token验证，这里简化处理）
     */
    @GetMapping("/user/info")
    public ApiResult<Object> getUserInfo(@RequestParam String openid) {
        try {
            if (openid == null || openid.trim().isEmpty()) {
                return ApiResult.error(400, "openid不能为空");
            }
            
            User user = loginService.getUserByOpenid(openid);
            if (user != null) {
                // 不返回敏感信息
                user.setSessionKey(null);
                return ApiResult.success("获取成功", user);
            } else {
                return ApiResult.error(404, "用户不存在");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.error("获取用户信息失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取内置头像列表
     */
    @GetMapping("/avatars")
    public ApiResult<Object> getAvatars() {
        try {
            // 返回内置头像列表（本地路径）
            List<String> avatars = new ArrayList<>();
            for (int i = 1; i <= 6; i++) {
                avatars.add("/assets/avatars/avatar" + i + ".svg");
            }
            return ApiResult.success("获取成功", avatars);
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.error("获取头像列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 更新用户信息（用户名和头像）
     */
    @PostMapping("/user/update")
    public ApiResult<Object> updateUserInfo(@RequestBody Map<String, Object> updateData) {
        try {
            String openid = (String) updateData.get("openid");
            String username = (String) updateData.get("username");
            String avatarUrl = (String) updateData.get("avatarUrl");
            
            System.out.println("[LoginController] Received update request:");
            System.out.println("[LoginController] openid: " + openid);
            System.out.println("[LoginController] username: " + username);
            System.out.println("[LoginController] avatarUrl: " + avatarUrl);
            
            if (openid == null || openid.trim().isEmpty()) {
                return ApiResult.error(400, "openid不能为空");
            }
            
            if (username == null || username.trim().isEmpty() || 
                username.trim().length() < 2 || username.trim().length() > 10) {
                return ApiResult.error(400, "用户名长度必须在2-10个字符之间");
            }
            
            // 调用service层更新用户信息
            User updatedUser = loginService.updateUserInfo(openid, username.trim(), avatarUrl);
            
            return ApiResult.success("更新成功", updatedUser);
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResult.error("更新用户信息失败: " + e.getMessage());
        }
    }
}
